package com.csproj.siiat.base.common.service;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/websocket/{ip}")
@Component
public class WebsocketUDP {

    private static int onlineCount = 0;
    private static Map<String, WebsocketUDP> clients = new ConcurrentHashMap<String, WebsocketUDP>();
    private Session session;
    private String ip;

    @OnOpen
    public void onOpen(@PathParam("ip") String ip, Session session) throws IOException {

        this.ip = ip;
        this.session = session;

        addOnlineCount();
        clients.put(ip, this);
        System.out.println("已连接");
    }

    @OnClose
    public void onClose() throws IOException {
        clients.remove(ip);
        subOnlineCount();
    }

    @OnMessage
    public void onMessage(String message) throws IOException {


    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    public void sendMessageTo(String message, String To) throws IOException {
        for (WebsocketUDP item : clients.values()) {
            if (item.ip.equals(To) )
                item.session.getAsyncRemote().sendText(message);
        }
    }

    public void sendMessageAll(String message) throws IOException {
        for (WebsocketUDP item : clients.values()) {
            item.session.getAsyncRemote().sendText(message);
        }
    }



    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebsocketUDP.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebsocketUDP.onlineCount--;
    }

    public static synchronized Map<String, WebsocketUDP> getClients() {
        return clients;
    }

}
